<?php include("MathFuncs.php");
      include("QuestionDefinition.php");
      include("Question.php");

class QuestionAssembler
{
   private $varsArray;
   private $exprArray;
   private $varTable;
   private $solutionArray;

   private $questionDefn;

   public function build($def) {
      $this->questionDefn = $def;

      unset($varTable);
      $vars = explode("\n", $def->definition);
      foreach ($vars as $expr) {
         $tok = strtok($expr, "=");
	 $tok = trim($tok);
	 if ($tok != false) {
	    $this->varsArray[] = $tok;
	    $this->exprArray[$tok] = strtok("=");
	 }
      }

      $this->generateVars();
   }

   private function scopeFunctions($expr) {
      $expr = preg_replace("/([a-zA-Z0-9])+\(/", "MathFuncs::$0", $expr);
      return $expr;
   }

   public function generateVars() {
      foreach ($this->varsArray as $var) {
         $expr = $this->exprArray[$var];
	 $expr = $this->substituteValues($expr);

	 #evaluate the expr now
	 $expr = $this->scopeFunctions($expr);
	 eval("\$temp = $expr");
	 $this->varTable[$var] = $temp;
	 #print $var . " = " . $expr . " = " . $temp . "<br>";
      }
      $expr = $this->substituteValues($this->questionDefn->solution);
      $expr = $this->scopeFunctions($expr);
      eval("\$temp = $expr");
      $this->solutionArray = $temp;
   }

   private function substituteValues($str) {
      while (($pos = strpos($str, "%")) !== false) {
         $old = substr($str, $pos, 2);
	 $var = substr($str, $pos+1, 1);
   	 $new = $this->varTable[$var];
	 $str = str_replace($old, $new, $str);
      }
      return $str;
   }

   public function getTestQuestion() {
      $expr = $this->questionDefn->question;
      $expr = $this->substituteValues($expr);
      $question = MathFuncs::cleanUp($expr);

      $expr = $this->questionDefn->answer;
      $expr = $this->substituteValues($expr);
      $answer = $expr;

      $numSolutions = count($this->solutionArray);
      for ($i = 0; $i < $numSolutions; $i++) {
         $soln = $this->solutionArray[$i];
	 $soln = $this->substituteValues($soln);
	 $this->solutionArray[$i] = $soln;
      }

      $problem = new Question($question, $answer, $this->questionDefn->solutionFn, $this->solutionArray, $this->questionDefn->flags);
      $problem->templateId = $this->questionDefn->templateId;
      return $problem;
   }
}